package org.scboy.coobi.db.style;

import org.apache.calcite.config.Lex;
import org.apache.calcite.sql.dialect.MysqlSqlDialect;
import org.apache.calcite.sql.validate.SqlConformanceEnum;
import org.scboy.coobi.db.context.DbStyleContext;
import org.scboy.coobi.db.mapping.DataTypeMapping;
import org.scboy.coobi.db.mapping.mysql.MySqlDataTypeMapping;
import org.scboy.coobi.entity.SqlConvertSchame;
import org.scboy.utils.entitys.coobi.DbColumn;

import cn.hutool.core.util.StrUtil;

/**
 * Mysql 数据库操作类
 */
public class MysqlStyle extends DbStyleContext {

	@Override
	public String getDb() {
		return "mysql";
	}

	@Override
	public String getJdbc() {
		return "jdbc:mysql";
	}
	
	@Override
	public DataTypeMapping getDataTypeMapping() {
		return new MySqlDataTypeMapping();
	}

	@Override
	public String getExistsColumnSql(String tabName, String colName) {
		String sql="";
		if(StrUtil.isNotEmpty(colName)){
			sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '"+this.dbName+"' AND TABLE_NAME = '"+tabName+"' AND COLUMN_NAME = '"+colName+"'";
			return this.sqlFormat(sql);
		}else {
			sql = "SHOW TABLES LIKE '"+tabName+"'";
			return sql;
		}
	}
	
	@Override
	public String getAddColumnCommentSql(String name, DbColumn column) {
		StringBuilder builder=new StringBuilder();
		builder.append("ALTER TABLE ");
		builder.append(this.getFormatName(name));
		builder.append(" MODIFY ");
		builder.append(this.getFormatName(column.getName()));
		builder.append(" COMMENT '");
		builder.append(column.getComment());
		builder.append("'");
		return builder.toString();
	}

	@Override
	public String getAddTableCommentSql(String name, String comment) {
		StringBuilder builder=new StringBuilder();
		builder.append("ALTER TABLE ");
		builder.append(this.getFormatName(name));
		builder.append(" COMMENT '");
		builder.append(comment);
		builder.append("'");
		return builder.toString();
	}

	@Override
	public String getExistsIndexSql(String tableName, String indexName) {
		String sql="SELECT index_name FROM information_schema.statistics WHERE table_schema = '"+dbName+"' AND table_name = '"+tableName+"' AND index_name = '"+indexName+"'";
		return this.sqlFormat(sql);
	}

	@Override
	public String getPageSql(String sql, int start, int limit) {
		sql = sql + " OFFSET "+start+" ROWS FETCH NEXT "+limit+" ROWS ONLY ";
		return sql;
	}

	@Override
	public SqlConvertSchame getSchame() {
		return new SqlConvertSchame(Lex.MYSQL,SqlConformanceEnum.MYSQL_5,MysqlSqlDialect.DEFAULT);
	}

	@Override
	public String getRString() {
		return "`";
	}

	@Override
	public String getLString() {
		return "`";
	}

}
